// 检测屏幕尺寸并在页面加载时应用样式
let isMobile = window.innerWidth <= 768

// 检查屏幕尺寸并设置类名
function updateLayoutClass() {
    const html = document.documentElement;
    if (isMobile) {
        html.className = 'mobile'
    } else {
        html.className = 'pc'
    }
}

// 活动上传作品的开始时间和结束时间
let startTime = new Date("2024-09-23T00:00:00").getTime(); // 使用时间戳
let endTime = new Date("2024-11-10T23:59:59").getTime();

// 获取当前时间的时间戳
function getCurrentTimeTimestamp() {
    return new Date().getTime();
}

// 检查当前时间是否在开始和结束时间范围内
function isWithinTimeRange(startTime, endTime) {
    let currentTime = getCurrentTimeTimestamp();
    return currentTime >= startTime && currentTime <= endTime;
}

// 更新倒计时元素的显示
function updateCountdownElement(elementClass, days) {
    const countdownElement = document.querySelector(`.${elementClass}`);
    if (days > 0) {
        countdownElement.textContent = days;
    } else {
        countdownElement.textContent = '0';
    }
}

// 根据当前时间更新 fixed-card 的显示/隐藏状态和倒计时
function updateFixedCardAndCountdown() {
    if (isWithinTimeRange(startTime, endTime)) {
        const uploadBtn = document.querySelector('.pc-upload-btn');

        // 计算倒计时
        let timeLeft = endTime - getCurrentTimeTimestamp();
        let daysLeft = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
        updateCountdownElement('count-down-interval', daysLeft);
    } else {
        const uploadBtn = document.querySelector('.pc-upload-btn');
        const countdownElement = document.querySelector('.count-down-interval');
        countdownElement.textContent = '0';
        uploadBtn.disabled = true;
    }
}

// 检查滚动位置并控制fixed-card的显示和隐藏
function checkScrollPositionAndShowFixedCard() {
    const scrollPosition = window.scrollY;
    const videoPlayerHeight = document.querySelector('.pc-player-block').offsetHeight;
    const imgHeight = document.querySelector('.pc-player-block').offsetHeight;
    const backTop = document.querySelector('.back-top');

    if (isMobile) {
        if (scrollPosition > imgHeight) {
            backTop.style.display = 'block';
        } else {
            backTop.style.display = 'none';
        }
    } else {
        if (scrollPosition > videoPlayerHeight) {
            backTop.style.display = 'block';
        } else {
            backTop.style.display = 'none';
        }
    }
}

// 平滑返回顶部
function backToTop() {
    document.querySelector('.back-top').addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth' // 实现平滑滚动
        });
    });
}

// 平滑过渡到对应区域 - 前置函数
function smoothToContent() {
    document.querySelectorAll('.navi-block-menu li').forEach((item, index) => {
        item.addEventListener('click', () => {
            const sectionId = ['intro-section', 'awards-section', 'design-section', 'instructions-section', 'schedule-section', 'review-section', 'conference-section', 'jai-section'][index];
            const currentURL = window.location.href;
            const isEnglish = currentURL.includes('-en.html'); // 检查是否为英文页面

            switch (sectionId) {
                case 'intro-section':
                case 'awards-section':
                case 'design-section':
                case 'instructions-section':
                case 'schedule-section':
                    // 如果当前页面不是正确的主页，跳转到对应的主页并传递sectionId作为参数
                    if (isEnglish && !currentURL.includes('index-en.html')) {
                        window.location.href = `index-en.html?section=${sectionId}`;
                    } else if (!isEnglish && !currentURL.includes('index.ftl')) {
                        window.location.href = `index.ftl?section=${sectionId}`;
                    } else {
                        toAnchorView(sectionId); // 如果在正确的主页，直接平滑滚动
                    }
                    break;
            }
        });
    });
}

// 平滑过渡到对应区域 - 执行函数
function toAnchorView(data) {
    const $choose = document.querySelector(`.${data}`);
    if ($choose) {
        $choose.scrollIntoView({ behavior: 'smooth', block: 'start' });
        window.scrollTo({
            left: 0,
            top: $choose.offsetTop - 184,
            behavior: 'smooth'
        });
    }
}

// 控制导航菜单的sticky切换
function toggleStickyNavigation() {
    const playerBlockHeight = document.querySelector(".pc-player-block").offsetHeight;
    const menu = document.querySelector(".navi-block-menu");
    const currScrollTop = document.documentElement.scrollTop || document.body.scrollTop || window.scrollY;
    if (currScrollTop > playerBlockHeight) {
        menu.classList.remove("navi-default");
        menu.classList.add("navi-sticky");
    } else {
        menu.classList.remove("navi-sticky");
        menu.classList.add("navi-default");
    }
}

// 语言切换函数
function switchLanguage(language) {
    const currentURL = window.location.href;

    let newURL;

    // 根据当前页面和选择的语言，设置新的 URL
    if (language === "0") {
        if (currentURL.includes("-en.html")) {
            newURL = currentURL.replace("-en.html", ".html");
        }
    } else if (language === "1") {
        if (!currentURL.includes("-en.html")) {
            newURL = currentURL.replace(".html", "-en.html");
        }
    }

    // 如果有新URL，跳转到新URL
    if (newURL && newURL !== currentURL) {
        window.location.href = newURL;
    }
}

// 页面加载时设置 select 默认选项
function setLanguageDefault() {
    const currentURL = window.location.href;
    const languageSelect = isMobile ? document.querySelectorAll('.switch-language>select')[0] : document.querySelectorAll('.switch-language>select')[1];

    // 如果当前 URL 包含 "-en.html"，则设置语言选项为英文
    if (currentURL.includes("-en.html")) {
        languageSelect.value = "1";
    } else {
        languageSelect.value = "0";
    }
}

// 校徽、学院徽章点击跳转页面
function badgeClickJump() {
    const jai = document.querySelector('.img-jai')
    const game = document.querySelector('.img-game')
    // 绑定吉林动画学院徽章点击跳转事件
    if (jai) {
        jai.addEventListener('click', function() {
            window.open('https://www.jlai.edu.cn/', '_blank');
        });
    }
    // 绑定游戏学院徽章点击跳转事件
    if (game) {
        game.addEventListener('click', function() {
            window.open('http://yx.jlai.edu.cn/', '_blank');
        });
    }
}

// 立即报名
function signUpNow() {
    const btn = isMobile ? document.querySelector('.mobile-upload-btn') : document.querySelector('.pc-upload-btn');
    const isEnglish = window.location.href.includes('-en.html'); // 检查是否为英文页面

    if (btn) {
        // 检查当前时间是否在活动时间范围内
        if (!isWithinTimeRange(startTime, endTime)) {
            btn.disabled = true;
            btn.classList.add(isMobile ? 'mobile-upload-btn-disabled' : 'pc-upload-btn-disabled');
        } else {
            btn.addEventListener('click', () => {
                const targetPage = isEnglish ? 'registration-en.html' : 'registration.html';
                window.location.href = targetPage;
            });
        }
    }
}

// 滚动到往届回顾位置
function scrollToReviewSessions() {
    const formSection = document.querySelector('.review-sessions');

    if (formSection) {
        formSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        window.scrollTo({
            top: formSection.offsetTop - 184,
            behavior: 'smooth'
        });
    }
}

// 移动端-打开菜单
function openMenu() {
    const menuDom = document.querySelector('.mobile-menu-content');
    if (menuDom) {
        menuDom.style.display = 'flex';
        menuDom.className = `mobile-menu-content menu-content-show`;
    }
}

// 移动端-关闭菜单
function closeMenu() {
    const menuDom = document.querySelector('.mobile-menu-content');
    if (menuDom) {
        menuDom.className = `mobile-menu-content menu-content-close`;
    }
}

window.addEventListener('scroll', () => {
    updateFixedCardAndCountdown()
    checkScrollPositionAndShowFixedCard()
    toggleStickyNavigation()
});

window.addEventListener('DOMContentLoaded', () => {
    updateLayoutClass()
    updateFixedCardAndCountdown()
    backToTop()
    smoothToContent()
    setLanguageDefault()
    badgeClickJump()
    signUpNow()
    scrollToReviewSessions()
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
    // 重新检查屏幕尺寸
    isMobile = window.innerWidth <= 768;
    updateLayoutClass()
    scrollToSection()
    updateFixedCardAndCountdown()
    backToTop()
    smoothToContent()
    setLanguageDefault()
    badgeClickJump()
    signUpNow()
});
